// 防抖
export const debounce = (fn: (arg?: unknown) => void, timeout: number) => {
  let timer: NodeJS.Timeout;
  return (arg?: unknown) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn(arg);
    }, timeout);
  };
};

// 带次数的防抖，超过次数都没有执行 fn，则不再延迟，直接执行
export const debounceWithMax = (fn: (arg?: unknown) => void, timeout: number, max: number) => {
  let timer: NodeJS.Timeout;
  let count: number = 0;
  return (arg_?: unknown) => {
    if (timer) {
      clearTimeout(timer);
    }
    if (++count > max) {
      fn(arg_);
      count = 0;
    } else {
      timer = setTimeout(() => {
        fn(arg_);
        count = 0;
      }, timeout);
    }
  };
};
